package com.app.conrtoller;

import com.alibaba.fastjson.JSON;
import com.app.domain.ExternalResponse;
import com.app.domain.UploadParameter;
import com.app.domain.YjData;
import com.app.domain.yxtj.GroutingProcess;
import com.app.domain.yxtj.YxtjGrouting;
import com.app.domain.yxtj.YxtjResultJson;
import com.app.service.SendMessageService;
import com.app.service.UploadParameterService;
import com.app.service.UploadService;
import com.app.service.YjDataService;
import com.app.service.algs.AlgsUploadService;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/xsgs")
public class XsgsController {
    @Value("${yj.xsgs.serverHost}")
    private String serverHost;
    @Value("${yj.xsgs.processHost}")
    private String processHost;
    @Value("${yj.xsgs.ProjectGUID}")
    private String ProjectGUID;
    @Value("${yj.xsgs.SectionGUID}")
    private String SectionGUID;
    @Value("${yj.xsgs.SectionCode}")
    private String SectionCode;
    @Value("${yj.xsgs.FactoryCode}")
    private String FactoryCode;
    @Autowired
    YjDataService yjDataService;
    @Autowired
    UploadParameterService uploadParameterService;
    @Autowired
    UploadService uploadService;
    @Autowired
    AlgsUploadService algsUploadService;
    @Autowired
    SendMessageService sendMessageService;

    @RequestMapping("/upload")
    @ResponseBody
    public ExternalResponse upload(@RequestParam(value = "ids[]") String[] ids) throws InterruptedException {
        ExternalResponse externalResponse = null;
        int total = ids.length;
        int succTotal = 0;
        int failTotal = 0;
        StringBuffer responseContent = new StringBuffer();
        responseContent.append("本次共上传数据：【" + total + "】条,");


        List<YjData> yjDataList = yjDataService.findList(ids);
        List<List<YjData>> groupList = new ArrayList<>();
        yjDataList.stream().collect(Collectors.groupingBy(YjData::getBridge_code, Collectors.toList())).forEach((bridge_code, yjDataGroupList) -> {
            groupList.add(yjDataGroupList);
        });
        UploadParameter uploadParameter = uploadParameterService.findOne("21");
        for (List<YjData> yjData : groupList) {
            List<Integer> userIds = yjData.stream().map(o -> o.getId()).collect(Collectors.toList());
            Map<String, Object> map = yjDataService.findDate(userIds);
            Map<String, Object> map1 = algsUploadService.getGrouting(yjData, uploadParameter, ProjectGUID, SectionGUID, SectionCode, FactoryCode, map);
            YxtjGrouting grouting = (YxtjGrouting) map1.get("grouting");
            List<GroutingProcess> groutingProcessList = (List<GroutingProcess>) map1.get("process");
            String s = JSON.toJSONString(grouting);
            YxtjResultJson resultJson = uploadService.sendYxtjMessage(serverHost, s);

            if (200 == resultJson.getCode()) {
                log.info("信随高速压浆主表上传成功");
                int count = 0;
                List<List<GroutingProcess>> partition = Lists.partition(groutingProcessList, 20);
                for (List<GroutingProcess> groutingProcesses : partition) {
                    String s1 = JSON.toJSONString(groutingProcesses);
                    YxtjResultJson resultJson1 = uploadService.sendYxtjMessage(processHost, s1);
                    if (200 == resultJson1.getCode()) {
                        count++;
                    }
                }
                if (count == partition.size()) {
                log.info("信随高速压浆曲线上传成功");
                }
                for (Integer userId : userIds) {
                    updateState("1", String.valueOf(userId));
                    succTotal++;
                }

            } else {
                for (Integer userId : userIds) {
                    updateState("0", String.valueOf(userId));
                    failTotal++;
                }
            }
        }
        responseContent.append("成功【" + succTotal + "】条,失败" + failTotal + "条");
        externalResponse = new ExternalResponse(0, responseContent.toString(), "");
        return externalResponse;
    }

    private void updateState(String state, String id) {
        yjDataService.updateById(state, id);
    }
}
